<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>登录</title>
    <link rel="stylesheet" href="/css/style.css"/>
</head>
<body>
<div class="center-container">
    <h1>应急图书管理系统 - 登录</h1>
    <form id="loginForm" class="center-form">
        <label>用户名: <input type="text" name="username" required></label><br>
        <label>密码: <input type="password" name="password" required></label><br>
        <button type="submit">登录</button>
    </form>
    <p><a href="/user/register">没有账号？点击注册</a></p>
</div>
<script>
    document.getElementById('loginForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);
        const response = await fetch('/user/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams(data).toString()
        });
        const result = await response.json();
        if (result.code === 0) {
            localStorage.setItem('token', result.data);
            localStorage.setItem('username', result.username);
            localStorage.setItem('userType', result.userType || 'user');
            localStorage.setItem('userId', result.userId || '');

            alert(result.message);


            // 根据 userType 判断跳转地址
            if (result.userType === 'super') {
                window.location.href = '/user/index';
            } else {
                window.location.href = '/book/student/books';
            }
        } else {
            alert(result.message);
        }
    });
</script>
</body>
</html>